#!/usr/bin/env python3

import pendulum
import os
import sys
sys.path.append(f'{os.path.dirname(os.path.realpath(__file__))}/../utils')
sys.path.append(f'{os.path.dirname(os.path.realpath(__file__))}/../operators')
import wrf_operators as wrf
from utils import cmd_args, cli, parse_config, run

args = cmd_args()

config = parse_config(args.config_json)

if args.start_time:
	config['custom']['start_time'] = args.start_time
else:
	args.start_time = config['custom']['start_time']

def run_fcst(work_root, config, args):
	start_time = config['custom']['start_time']
	end_time = start_time.add(days=config['custom']['be']['run_days'])
	for time in pendulum.period(start_time, end_time).range('hours', config['custom']['be']['fcst_interval_hours']):
		config['custom']['start_time'] = time
		config['custom']['end_time'] = time + pendulum.duration(hours=config['custom']['forecast_hours'])
		work_dir = f'{work_root}/{time.format("YYYYMMDDHH")}'
	
		wrf.config_wps(work_root, args.wps_root, args.geog_root, config, args)
		wrf.run_wps_geogrid(work_root, args.wps_root, config, args)
		wrf.config_wps(work_dir, args.wps_root, args.geog_root, config, args)
		wrf.run_wps_ungrib_metgrid(work_dir, args.wps_root, args.bkg_root, config, args, geogrid_work_dir=work_dir+'/../wps')
	
		wrf.config_wrf(work_dir, args.wrf_root, config, args)
		wrf.run_real(work_dir, args.wrf_root, config, args)
		wrf.run_wrf(work_dir, args.wrf_root, config, args)

		run(f'ln -sf {work_dir}/wrf/wrfout_d01_{time.add(hours=12).format("YYYY-MM-DD_HH:mm:SS")} {work_dir}/')
		run(f'ln -sf {work_dir}/wrf/wrfout_d01_{time.add(hours=24).format("YYYY-MM-DD_HH:mm:SS")} {work_dir}/')

run_fcst(args.work_root, config, args)
